package com.atguigu.gulimall.order.web;

import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;

    /**
     * 订单结算页
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("confirmOrderData",confirmVo);
        //展示订单确认的数据

        return "confirm";
    }

    /**
     * 下单
     * 1.校验订单令牌token,校验成功进行下单操作，校验失败返回code=1
     *
     * 2.构建订单数据
     *     （1）订单号
     *     （2）购物车商品信息：应该直接查询购物车数据，不能获取结算页的商品数据，
     *     （3）用户信息
     *     （4）下单金额（验价） 根据购物车商品信息进行验价
     *
     * 3.下单成功，锁库存，跳转到支付页
     *   下单失败，调回到订单页 -> 重新确认订单信息
     *      下单失败原因：重复提交页面，下单金额对比不一致，商品库存不足
     */
    @PostMapping("/submitOrder")
    public String submitOrder(@Valid OrderSubmitVo submitVo, Model model, RedirectAttributes attributes){//form表单提交不能加@RequestBody，@RequestBody是json转java

        SubmitOrderResponseVo responseVo = orderService.placeOrder(submitVo);
        if (responseVo.getCode() == 0){
            model.addAttribute("submitOrderResp",responseVo);
            return "pay";
        }else {
            String msg = "下单失败";
            switch (responseVo.getCode()) {
                case 1: msg += "令牌订单信息过期，请刷新再次提交"; break;
                case 2: msg += "订单商品价格发生变化，请确认后再次提交"; break;
                case 3: msg += "库存锁定失败，商品库存不足"; break;
            }
            attributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }


}
